<!--
 * @FilePath: gifi-count.vue
 * @@author: wjj
 * @Date: 2025-05-18 10:48:36
 * @@Description: new js file
-->
<!--
 * @FilePath: gifi-count.vue
 * @@author: wjj
 * @Date: 2025-05-18 10:48:36
 * @@Description: new js file
-->
<template>
  <div>
    <el-form
      class="login_form"
      :model="GiftForm"
      :rules="rules"
      ref="GiftForms"
      :inline="true"
    >
      <!-- @keyup.enter="login" -->
      <!-- :inline="true" -->
      <el-row>
        <h1 style="margin-left: 40%; margin-right: 30%; margin-bottom: 10px">
          活动概率统计
        </h1>
      </el-row>

      <el-form-item prop="URL_name" size="small" style="width: 1085px" label="">
        <el-input style="" type="text" v-model="GiftForm.URL_name" clearable>
          <template #prepend>
            <el-select v-model="select" placeholder="活动" style="width: 115px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login_btn"
          type="primary"
          plain
          size="default"
          @click="start"
          :disabled="btustatus"
          v-has="`btn.GiftCount.start`"
        >
          {{ startstr }}
        </el-button>
        <el-button
          type="primary"
          @click="addConf"
          size="small"
          v-has="`btn.GiftCount.addconfig`"
          plain
        >
          添加功能
        </el-button>
        <el-button
          type="primary"
          @click="updateConf"
          size="small"
          v-has="`btn.GiftCount.updateconfig`"
          plain
        >
          编辑
        </el-button>
        <el-popconfirm
          :title="`你确定要删除?`"
          width="260px"
          @confirm="removeConf"
        >
          <template #reference>
            <el-button
              type="primary"
              size="small"
              v-has="`btn.GiftCount.deleteconfig`"
              plain
            >
              删除
            </el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
      <el-row>
        <!-- :prefix-icon="Lock" -->
        <el-form-item prop="forNumber" size="small" label="循环次数">
          <!-- <span style="margin-right: 5px">循环次数</span> -->
          <el-input-number
            v-model="GiftForm.forNumber"
            :min="1"
            :max="10000"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="oneNumber" size="small" label="单次数">
          <!-- <span style="margin-right: 5px">单次数</span> -->
          <el-input-number
            v-model="GiftForm.oneNumber"
            :min="1"
            :max="10000000"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="timeNumber" size="small" label="时间">
          <!-- <span style="margin-right: 5px">时间</span> -->
          <el-input-number
            v-model="GiftForm.timeNumber"
            :min="0"
            :max="30"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="yongstr" size="small" style="width: 150px">
          <el-input style="" type="text" v-model="GiftForm.yongstr" clearable>
            <template #prepend>
              <span style="width: 10px">泳道</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="device_id" size="small" style="width: 150px">
          <el-input style="" type="text" v-model="GiftForm.device_id" clearable>
            <template #prepend>
              <span style="width: 10px">设备</span>
            </template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item prop="device_id" size="small" style="width: 150px">
          <el-button
            class="login_btn"
            type="primary"
            plain
            size="default"
            @click="ROI"
          >
            ROI
          </el-button>
        </el-form-item> -->
      </el-row>
      <el-row>
        <el-form-item
          prop="authstr"
          size="small"
          style="width: 350px; margin-right: 0px"
          v-if="!pthoneStatus"
        >
          <el-input style="" type="text" v-model="GiftForm.authstr" clearable>
            <template #prepend>
              <span style="width: 10px">auth</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="phoneNumber"
          size="small"
          style="width: 350px"
          v-if="pthoneStatus"
        >
          <span style="width: 15%">手机号</span>
          <el-input-number
            v-model="GiftForm.phoneNumber"
            :min="0"
            style="width: 85%"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-tooltip class="box-item" effect="dark" placement="top-start">
            <template #content>
              使用auth，不会将当前账户挤下来
              <br />
              使用手机号，无需获取auth，但账号会被挤下来
              <br />
              也可以直接使用这个账号
            </template>
            <el-switch
              v-model="pthoneStatus"
              inline-prompt
              active-text="phone"
              inactive-text="phone"
              style=""
              :disabled="btustatus"
            />
          </el-tooltip>
        </el-form-item>

        <el-form-item
          prop="rulestr"
          size="small"
          style="width: 350px; margin-right: 0px; margin-left: 20px"
        >
          <el-row></el-row>
          <el-input
            style="width: 100%"
            type="text"
            v-model="GiftForm.rulestr"
            clearable
          >
            <template #prepend>
              <span style="width: 10px">规则</span>
            </template>
          </el-input>
        </el-form-item>
        <el-tooltip class="box-item" effect="dark" placement="top-start">
          <template #content>
            自定义规则
            <br />
            $.data:代表响应数据中的data的值
            <br />
            $.name:代表data中的name值也是数据展示中的礼物名
            <br />
            $.price:代表data中的price值也是数据展示中的价值
            <br />
            $.total_nums:代表data中的total_nums值也是数据展示中的数量
            <br />
            总礼物数是循环次数*单次数
          </template>
          <el-icon style="margin-top: 4px"><QuestionFilled /></el-icon>
        </el-tooltip>
        <el-button
          class="login_btn"
          type="primary"
          plain
          size="default"
          @click="resStatus"
          :disabled="btustatus"
          style="margin-left: 20px"
        >
          {{ res_str }}
        </el-button>
        <span style="margin-top: 7px; margin-left: 5px">
          目前出错{{ res_error_count }}个
        </span>
      </el-row>
      <el-row>
        <!-- <json-viewer
          :value="tableData"
          :expand-depth="5"
          copyable
          :boxed="true"
          sort
          :show-array-index="false"
        ></json-viewer>
        <codemirror
          ref="myCm"
          v-model="tableData"
          :options="cmOptions"
          class="code-mirror-height"
        ></codemirror> -->
        <div class="json-input">
          <div style="display: flex; align-items: center">
            <el-input
              v-model="GiftForm.jsonstr"
              type="textarea"
              :rows="10"
              placeholder="请输入 JSON 数据"
              :class="{ 'error-border': hasError }"
              @blur="validateJSON"
              style="width: 1000px"
            />

            <el-input
              v-model="res"
              type="textarea"
              :rows="10"
              disabled
              placeholder="响应数据"
              style="margin-left: 20%"
              class="resData"
            />
          </div>

          <div v-if="hasError" class="error-message">
            {{ errorText }}
          </div>
        </div>
        <!-- <JsonViewer
          :value="json_view"
          :expand-depth="5"
          copyable
          :boxed="true"
          sort
          :show-array-index="false"
        /> -->
      </el-row>
    </el-form>
    <el-switch
      v-model="chartsStatus"
      inline-prompt
      active-text="图形"
      inactive-text="图形"
      style=""
      :disabled="btustatus"
    />
    <div v-if="!chartsStatus">
      总次数：
      <el-input
        v-model="activity_count"
        :min="1"
        style="width: 100px"
      ></el-input>
      单价
      <el-input v-model="one_price" :min="1" style="width: 100px"></el-input>
      <el-button
        type="primary"
        plain
        size="default"
        @click="ROI"
        style="margin-left: 5px"
      >
        ROI
      </el-button>
      <span
        style="color: red; font-weight: bold; margin-left: 5px"
        v-if="ROI_status"
      >
        统计结果：{{ ROI_count }}/{{ activity_count * one_price }} =
        {{ ROI_count / (activity_count * one_price) }}
      </span>

      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column prop="gift" label="礼物" width="380" />
        <el-table-column prop="price" label="价值" width="180" />
        <el-table-column prop="count" label="数量" width="180" />
        <el-table-column prop="pro" label="概率" width="180" />
      </el-table>
    </div>
    <!-- <el-button type="success" @click="test">跳转测试</el-button> -->

    <div class="gift_charts" ref="charts" v-if="chartsStatus"></div>
  </div>
  <el-dialog
    v-model="dialogStatus"
    :title="confData.id ? '更新配置' : '添加配置'"
    :destroy-on-close="true"
  >
    <!-- 表单组件:收集新增与已有的菜单的数据 -->
    <el-form :model="confData" :rules="conf_rules" ref="formConf">
      <el-form-item label="名称" prop="activity_name">
        <el-input
          placeholder="请你活动名称"
          v-model="confData.activity_name"
          style="width: 50%"
        ></el-input>
        <el-button type="primary" @click="copy" plain v-if="!confData.id">
          复制当前配置
        </el-button>
      </el-form-item>
      <el-form-item label="活动id" prop="activity_id">
        <el-input
          placeholder="请你输入活动id"
          v-model="confData.activity_id"
        ></el-input>
      </el-form-item>
      <el-form-item label="配置1" prop="config">
        <el-input
          v-model="confData.config"
          type="textarea"
          :rows="10"
          placeholder="请输入 参数 配置"
          style="width: 1000px"
        />
      </el-form-item>
      <el-form-item label="配置2" prop="jsonconfig">
        <el-input
          v-model="confData.jsonconfig"
          type="textarea"
          :rows="10"
          placeholder="请输入 JSON 配置"
          style="width: 1000px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogStatus = false" plain>取消</el-button>
        <el-button type="primary" @click="saveConf" plain>确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- <el-dialog v-model="ROI_count" title="ROI统计">
    <el-button
      class="login_btn"
      type="primary"
      plain
      size="default"
      @click="dao_ROI"
      style="margin-right: 10%"
      :disabled="ROI_data === undefined"
    >
      {{ ROI_data === undefined ? '没配置ROI' : ROI_data.name }}:{{
        gift_dao_count
      }}
    </el-button>
    <el-text class="mx-1" type="success">
      总花费：
      {{ GiftForm.forNumber * GiftForm.oneNumber * 50 }}金币(不打折)
    </el-text>
    <el-table :data="tempData" style="width: 100%">
      <el-table-column prop="gift" label="礼物" width="180" />
      <el-table-column prop="price" label="价值" width="180" />
      <el-table-column prop="count" label="数量" width="180" />
      <el-table-column prop="pro" label="概率" width="180" />
    </el-table>
  </el-dialog> -->
</template>

<script lang='ts' setup >
defineOptions({
  name: 'GiftCount',
})
//test
// import JsonViewer from 'vue-json-viewer'
// import { codemirror } from 'vue-codemirror'
// import '../cm-setting.ts'
//test
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import emmit from '@/utils/emitter'
import { User, Lock } from '@element-plus/icons-vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import useSocketClient from '@/store/socket/socket_client'
import request from '@/utils/request'

import * as echarts from 'echarts'
import { da } from 'element-plus/es/locale'

// 挂载完毕
// @ts-ignore
import JSONbig from 'json-bigint'
// json格式化
// @ts-ignore
// import { JsonViewer } from 'vue3-json-viewer'
import 'vue3-json-viewer/dist/index.css'
//ROI模块
let activity_count = ref(1000)
let one_price = ref(50)
let ROI_status = ref(false)
let ROI_count = ref(1)
let selectIdArr = ref<any[]>([])
const selectChange = (value: any) => {
  selectIdArr.value = value
  console.log(selectIdArr.value)
}
const ROI = () => {
  ROI_count.value = 0
  if (selectIdArr.value.length <= 0) {
    ElMessage.error('还没数据')
    return
  }
  if (one_price.value <= 0 || activity_count.value <= 0) {
    ElMessage.error('单价与总数不对')
    return
  }
  for (let index = 0; index < selectIdArr.value.length; index++) {
    const element = selectIdArr.value[index]
    // if (dao_key.length === 0 || dao_key.includes(element.gift)) {
    ROI_count.value = ROI_count.value + element.price * element.count
  }
  ROI_status.value = true
}
let res = ref()
let rule_values = ref('')
// let ROI_count = ref<boolean>(false)
let pthoneStatus = ref(true)
//TODO活动配置
let select_shuju: any = reactive({
  Child: {
    URL_name: '',
    rulestr: '',
    jsonstr: '',
    yongstr: '',
  },
})

let select = ref()
//选择器
let options = ref<any[]>([])
let count = 0
// 监听 select.value 的变化
watch(select, (newVal, oldVal) => {
  // Object.keys(select_shuju).forEach((key) => {
  //   console.log(`Key: ${key}, Value: ${select_shuju[key]}`)
  // })
  // Object.values(select_shuju).forEach((value) => {
  //   console.log(`Value: ${value}`)
  // })
  if (newVal) {
    // console.log(newVal)
    if (count != 0) {
      GiftForm.URL_name = select_shuju[newVal].URL_name
      GiftForm.rulestr = select_shuju[newVal].rulestr
      GiftForm.jsonstr = select_shuju[newVal].jsonstr
      GiftForm.yongstr = select_shuju[newVal].yongstr
      ROI_data.value = select_shuju[newVal].roi_data
      firstConfs(newVal)
    }
    count++
  }
})

let dialogStatus = ref<boolean>(false)
let formConf = ref()
let json_view = ref({})
let ROI_data = ref<any>({})
const firstConf = (first_data: any) => {
  Object.assign(getConfData, first_data)
  // console.log(first_data)
  select.value = {
    value: first_data.activity_id,
    label: first_data.activity_name,
  }
  // console.log(select)
  let temp_data = JSON.parse(first_data.config)
  // console.log(temp_data)
  GiftForm.URL_name = temp_data.URL_name
  GiftForm.rulestr = temp_data.rulestr
  GiftForm.yongstr = temp_data.yongstr
  GiftForm.jsonstr = first_data.jsonconfig
  ROI_data.value = temp_data.roi_data
  json_view.value = JSONbig.parse(first_data.jsonconfig)
  // console.log(GiftForm)
}
//初始配置
const firstConfs = (activity_id?: any) => {
  request
    .get('/nimi/activity/activity_conf/1/?activity_id=' + activity_id)
    .then((response: any) => {
      if (activity_id) {
        console.log('单次+++++++++++++++')
        Object.assign(getConfData, response.data)
      } else {
        let temp_list: any = []
        for (let index = 0; index < response.data.length; index++) {
          const element = response.data[index]
          // console.log(element)
          let config = JSON.parse(element.config)
          // console.log(config)

          temp_list.push({
            value: element.activity_id,
            label: element.activity_name,
          })
          select_shuju[element.activity_id] = {
            URL_name: config.URL_name,
            rulestr: config.rulestr,
            jsonstr: element.jsonconfig,
            yongstr: config.yongstr,
            roi_data: config.roi_data,
          }
        }

        // console.log(select_shuju)
        // console.log(select_shuju.Child.URL_name)
        options.value = temp_list
        console.log(options.value)
        firstConf(response.data[0])
      }
    })
    .catch((error: any) => {
      console.error(error)
    })
}
//获取的数据
onMounted(() => {
  // 使用 axios 发起 GET 请求(推荐)
  // firstConfs('童年记忆盲盒')
  firstConfs('')
})
let getConfData = reactive({
  id: 0,
  activity_name: '',
  activity_id: '',
  config: '',
  jsonconfig: '',
})
//携带的参数
let confData = reactive({
  id: 0,
  activity_name: '',
  activity_id: '',
  config: '',
  jsonconfig: '',
})
//自定义校验规则函数
const validatorConfig = (_rule: any, value: any, callback: any) => {
  // console.log(rule)
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length <= 0) {
    callback(new Error('不能为空'))
  } else {
    try {
      // 自动格式化,JSONbig处理大数字
      JSONbig.stringify(JSONbig.parse(value), null, 2)
      callback()
    } catch (e) {
      callback(new Error('json校验失败'))
    }
  }
}
const validatorJsonConfig = (_rule: any, value: any, callback: any) => {
  // console.log(rule)
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length <= 0) {
    callback(new Error('不能为空'))
  } else {
    try {
      // 自动格式化,JSONbig处理大数字
      JSONbig.stringify(JSONbig.parse(value), null, 2)
      callback()
    } catch (e) {
      callback(new Error('json校验失败'))
    }
  }
}
const conf_rules = {
  activity_name: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },

    // { type: 'number', message: 'age must be a number' },
  ],
  activity_id: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },

    // { type: 'number', message: 'age must be a number' },
  ],
  config: [
    { trigger: 'change', validator: validatorConfig },
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },

    // { type: 'number', message: 'age must be a number' },
  ],
  jsonconfig: [
    { trigger: 'change', validator: validatorJsonConfig },
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },

    // { type: 'number', message: 'age must be a number' },
  ],
}
//添加菜单按钮的回调
const addConf = () => {
  //清空数据
  Object.assign(confData, {
    id: 0,
    activity_name: '',
    activity_id: '',
    config: '',
    jsonconfig: '',
  })
  //对话框显示出来
  dialogStatus.value = true

  nextTick(() => {
    formConf.value.clearValidate()
  })
}
const copy = () => {
  Object.assign(confData, {
    id: 0,
    activity_name: getConfData.activity_name,
    activity_id: getConfData.activity_id,
    config: getConfData.config,
    jsonconfig: getConfData.jsonconfig,
  })
}
const updateConf = () => {
  Object.assign(confData, getConfData)

  //对话框显示出来
  dialogStatus.value = true
  //收集新增的菜单的level数值

  nextTick(() => {
    formConf.value.clearValidate('activity_name')
    formConf.value.clearValidate('activity_id')
    formConf.value.clearValidate('config')
    formConf.value.clearValidate('jsonconfig')
  })
}
const removeConf = () => {
  Object.assign(confData, getConfData)
  //清空数据
  request
    .delete('/nimi/activity/activity_conf/?id=' + confData.id)
    .then((response: any) => {
      if (response.code == 200) {
        ElMessage.success(response.msg)
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch((error: any) => {
      console.error(error)
    })
  emmit.emit('shuaxin')
}
//确定按钮的回调
const saveConf = async () => {
  //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
  await formConf.value.validate()
  if (confData.id) {
    request
      .put('/nimi/activity/activity_conf/1?id=' + confData.id, confData)
      .then((response: any) => {
        //对话框隐藏
        if (response.code == 200) {
          dialogStatus.value = false
          ElMessage.success(response.msg)
        } else {
          ElMessage.error(response.msg)
        }
      })
      .catch((error: any) => {
        console.error(error)
      })
  } else {
    // 使用 axios 发起 POST 请求，保存
    request
      .post('/nimi/activity/activity_conf/', confData)
      .then((response: any) => {
        //对话框隐藏
        dialogStatus.value = false
        ElMessage.success('保存成功')
      })
      .catch((error: any) => {
        console.error(error)
      })
  }
  emmit.emit('shuaxin')
}

//监听盲盒活动

let GiftForm = reactive({
  URL_name: '',
  rulestr: '',
  jsonstr: '',

  forNumber: 1,
  oneNumber: 1,
  timeNumber: 0.1,
  authstr:
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDg1NzU2NjYsImlhdCI6MTc0Nzk3MDg2NiwicGxhdGZvcm0iOjAsInN1YiI6IjQ1MDgwMTQ3Njc4NTE0MzgwOCJ9.6-1Ip3SsestgjDEvsh60_oOaparAz5ZFupeXdVC1vPk',
  yongstr: '',
  phoneNumber: 18818880000,
  device_id: '259914149e8d1336',
})

let auth_phone = ref()
auth_phone.value = GiftForm.authstr
// 监听 count 的变化
let temp: any =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDg1NzU2NjYsImlhdCI6MTc0Nzk3MDg2NiwicGxhdGZvcm0iOjAsInN1YiI6IjQ1MDgwMTQ3Njc4NTE0MzgwOCJ9.6-1Ip3SsestgjDEvsh60_oOaparAz5ZFupeXdVC1vPk'
watch(pthoneStatus, (newVal, oldVal) => {
  if (newVal) {
    GiftForm.phoneNumber = parseInt(temp)
    temp = GiftForm.authstr
    GiftForm.authstr = ''
    // GiftForm.phoneNumber = temp
    // GiftForm.phoneNumber = 18818880000
  } else {
    GiftForm.authstr = temp
    temp = GiftForm.phoneNumber
    GiftForm.phoneNumber = 0
    // GiftForm.authstr =temp
    // GiftForm.authstr = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
  }
})
let GiftForms = ref()
let startstr = ref('开 始')
let btustatus = ref(false)
const login = () => {
  GiftForms.value.validate()
  startstr.value = '请等待'
  btustatus.value = true
  setTimeout(() => {
    startstr.value = '开 始'
    btustatus.value = false
  }, 3000)
}

let res_str = ref('正确数据(可切换)')
let res_str_status = true
let res_error_count = ref(0)
let res_success = ref()
let res_error = ref()
const resStatus = () => {
  if (res_str_status) {
    res_str.value = '错误数据(可切换)'
    res_str_status = false
    if (res_error.value.length <= 1) {
      // res.value = JSON.stringify(res_error.value[0])
      res.value = JSONbig.stringify(res_error.value[0], null, 2)
    } else {
      // res.value = JSON.stringify(res_error.value)
      res.value = JSONbig.stringify(res_error.value, null, 2)
    }
  } else {
    if (res_error.value.length <= 1) {
      // res.value = JSON.stringify(res_success.value[0])
      res.value = JSONbig.stringify(res_success.value[0], null, 2)
    } else {
      // res.value = JSON.stringify(res_success.value)
      res.value = JSONbig.stringify(res_success.value, null, 2)
    }
    res_str.value = '正确数据(可切换)'
    res_str_status = true
  }
}
let count_num = ref(0)
let lei_num = ref(0)
emmit.on('gift_blind_box', (data: any) => {
  // console.log('收到事件', data[0])
  if (data == '结束了') {
    btustatus.value = false
  } else if (data.length == 3) {
    lei_num.value++
    count_num.value = lei_num.value * GiftForm.oneNumber
    chartDataX.value = data[0]
    chartDataC.value = data[1]
    chartDataG.value = data[2]
    myChart.value!.setOption(setChart())
  } else {
    res_error_count.value = data[1][1].length
    res_success.value = data[1][0]
    res_error.value = data[1][1]

    if (res_str_status) {
      if (data[1][0].length <= 1) {
        // res.value = JSON.stringify(data[1][0][0])
        res.value = JSONbig.stringify(data[1][0][0], null, 2)
      } else {
        // res.value = JSON.stringify(data[1][0])
        res.value = JSONbig.stringify(data[1][0], null, 2)
      }
    } else {
      if (data[1][1].length <= 1) {
        // res.value = JSON.stringify(data[1][1][0])
        res.value = JSONbig.stringify(data[1][1][0], null, 2)
      } else {
        // res.value = JSON.stringify(data[1][1])
        res.value = JSONbig.stringify(data[1][1], null, 2)
      }
    }
    tableData.value = data[0]
  }
})

let gift_dao_count = ref(0)
let dao_key = <any>[]

let tempData = ref<any[]>([])
let dao_data = ref<any[]>([])
const dao_ROI = () => {
  tempData.value = dao_data.value
}
// const ROI = () => {
//   gift_dao_count.value = 0
//   dao_data.value = []
//   tempData.value = []
//   if (tableData.value.length == 0) {
//     ElMessage.error('还没数据')
//     return
//   }
//   dao_key = ROI_data.value.key
//   console.log(ROI_data.value)
//   console.log(tableData.value)
//   //[{}]
//   for (let index = 0; index < tableData.value.length; index++) {
//     const element = tableData.value[index]
//     // if (dao_key.length === 0 || dao_key.includes(element.gift)) {
//     gift_dao_count.value = gift_dao_count.value + element.price * element.count
//     dao_data.value.push({
//       count: element.count,
//       gift: element.gift,
//       price: element.price,
//       pro: element.pro,
//     })
//     // }
//   }
//   console.log(gift_dao_count.value)
//   ROI_count.value = true
// }
const start = async () => {
  count_num.value = 0
  lei_num.value = 0
  await GiftForms.value.validate()
  btustatus.value = true
  tableData.value = []
  res.value = ''
  res_error_count.value = 0
  // 使用axios发起POST请求
  request
    .post(
      '/nimi/auth/gift/to_count',
      {
        URL_name: GiftForm.URL_name,
        forNumber: GiftForm.forNumber,
        oneNumber: GiftForm.oneNumber,
        timeNumber: GiftForm.timeNumber,
        authstr: GiftForm.phoneNumber ? GiftForm.phoneNumber : GiftForm.authstr,
        yongstr: GiftForm.yongstr,
        rulestr: GiftForm.rulestr,
        jsonstr: GiftForm.jsonstr,
        activity_id: getConfData.activity_id,
        device_id: GiftForm.device_id,
      },
      { timeout: GiftForm.forNumber * GiftForm.timeNumber + 30000 },
    )
    .then((response: any) => {
      if (response.code == 200) {
        ElMessage.success(response.msg)
      }
    })
    .catch((error: any) => {
      btustatus.value = false
      console.error(error)
    })
}
// 对象提前创建
let $router = useRouter()
//测试按钮
let chartDataC = ref([3999, 999, 200, 200, 500, 300, 2999])
let chartDataG = ref([0.02, 0.05, 0.23, 0.22, 0.22, 0.22, 0.04])
let chartDataX = ref([
  'Swan Lake Love',
  'True Love',
  'Meet love',
  'Romantic',
  'Mermaid',
  'GOLD',
  'Candlelight Dinner',
])
function test() {
  // console.log(chartDataC)
  Math.random()
  const intervalId = setInterval(() => {
    chartDataC.value[0] = Math.random() * 1000
    chartDataC.value[1] = Math.random() * 1000
    chartDataC.value[2] = Math.random() * 1000
    chartDataC.value[3] = Math.random() * 1000
    chartDataC.value[4] = Math.random() * 1000
    chartDataC.value[5] = Math.random() * 1000
    chartDataC.value[6] = Math.random() * 1000
    chartDataG.value[0] = Math.random()
    chartDataG.value[1] = Math.random()
    chartDataG.value[2] = Math.random()
    chartDataG.value[3] = Math.random()
    chartDataG.value[4] = Math.random()
    chartDataG.value[5] = Math.random()
    chartDataG.value[6] = Math.random()
    //eslint-disable
    myChart.value!.setOption(setChart())
  }, 500)
  // 10秒后停止定时器
  setTimeout(() => {
    clearInterval(intervalId)
    console.log('定时器已停止')
  }, 10000)
}
const rules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //type: 'number'数字
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  URL_name: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },
    // { type: 'number', message: 'age must be a number' },
  ],
  forNumber: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],

  oneNumber: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],

  timeNumber: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],

  authstr: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],

  rulestr: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],
  phoneNumber: [
    {
      required: true,
      //   min: 6,
      //   max: 15,
      message: '不能为空',
      trigger: 'change',
    },
  ],
}
const tableData = ref<any[]>([])
const cmOptions = {
  theme:
    // "monokai",
    'material',
  // "dracula",
  //  "idea",
  // "rubyblue",
  // this.cmTheme
  // !this.cmTheme || this.cmTheme === "default"
  //   ? "rubyblue"
  //   : this.cmTheme, // 主题
  mode: 'application/json',
  // "python",
  // "text/x-java",
  // !this.cmMode || this.cmMode === "default"
  //   ? "application/json"
  //   : this.cmMode, // 代码格式
  tabSize: 4, // tab的空格个数
  indentUnit: '', // 一个块（编辑语言中的含义）应缩进多少个空格
  autocorrect: true, // 自动更正
  spellcheck: true, // 拼写检查
  autoRefresh: true,
  lint: true, // 检查格式
  lineNumbers: true, // 是否显示行数
  lineWrapping: true, // 是否自动换行
  styleActiveLine: true, // line选择是是否高亮
  keyMap: 'sublime', // sublime编辑器效果
  matchBrackets: true, // 括号匹配
  smartIndent: true, //上下文缩进
  autoCloseBrackets: true, // 在键入时将自动关闭括号和引号
  matchTags: { bothTags: true }, // 将突出显示光标周围的标签
  foldGutter: true, // 可将对象折叠，与下面的gutters一起使用
  gutters: [
    'CodeMirror-lint-markers',
    'CodeMirror-linenumbers',
    'CodeMirror-foldgutter',
  ],
  highlightSelectionMatches: {
    minChars: 2,
    style: 'matchhighlight',
    showToken: true,
  },
}

// json格式一
const hasError = ref(false)
const errorText = ref('')

const validateJSON = () => {
  try {
    // JSONbig.parse(GiftForm.jsonstr)

    hasError.value = false
    errorText.value = ''
    // 自动格式化,JSONbig处理大数字
    GiftForm.jsonstr = JSONbig.stringify(
      JSONbig.parse(GiftForm.jsonstr),
      null,
      2,
    )
  } catch (e) {
    hasError.value = true
    errorText.value = `JSON 格式错误`
  }
}

// 数据图
//获取DOM节点

let myChart = ref<echarts.ECharts | null>(null) // ECharts 实例
let charts = ref<HTMLElement | null>(null) //Dom实例
let chartsStatus = ref(true)
// 生成彩虹渐变（适合大量数据）
function generateRainbowColors(count: number): string[] {
  const colors: string[] = []
  const goldenAngle = 137.5 // 黄金角度，创造自然分布

  for (let i = 0; i < count; i++) {
    // 1. 非均匀色相映射（黄金分割分布）
    const hue = (i * goldenAngle) % 360

    // 2. 动态饱和度（增强色彩活力）
    const saturation = 70 + 15 * Math.sin(i * 0.1)

    // 3. 感知亮度优化（CIE明度补偿）
    const lightness =
      55 +
      15 *
        (0.2126 * Math.cos((hue * Math.PI) / 180) +
          0.7152 * Math.cos(((hue + 120) * Math.PI) / 180) +
          0.0722 * Math.cos(((hue + 240) * Math.PI) / 180))

    colors.push(
      `hsl(${hue.toFixed(1)}, ${Math.min(95, Math.max(45, saturation)).toFixed(
        1,
      )}%, ${Math.min(85, Math.max(25, lightness)).toFixed(1)}%)`,
    )
  }
  return colors
}
// 生成10种不同色相
const dynamicColors = generateRainbowColors(100)
//切换首次加载
let setChart = () => {
  return {
    tooltip: {
      triggerOn: 'mousemove',
      show: true,
      trigger: 'item',
      axisPointer: {
        type: 'shadow',
      },
      showContent: true,
    },

    //标题组件
    title: {
      //主标题
      text: '礼物概率',
      link: 'http://www.baidu.com',
      //标题的位置
      left: '50%',
      //主标题文字样式
      textStyle: {
        color: 'yellowgreen',
        fontSize: 20,
      },
      //子标题
      subtext: '礼物总数' + count_num.value,
      //子标题的样式
      subtextStyle: {
        color: 'yellowgreen',
        fontSize: 16,
      },
    },
    //x|y轴组件

    xAxis: {
      type: 'category', //图形图标在x轴均匀分布展示
      //两侧不留白
      boundaryGap: false,
      //分割线不要
      splitLine: {
        show: false,
      },
      data: chartDataX.value,
      //刻度
      axisTick: {
        alignWithLabel: true,
        show: true,
      },
      axisLabel: {
        fontSize: 12,

        width: 50,
        overflow: 'truncate',
        interval: 0,
      },
      //轴线的设置
      axisLine: {
        show: true,
      },
      axisPointer: {
        type: 'shadow',
        value: '0',

        label: {
          show: true,
          // formatter: function (params: any) {
          // return 'ssad'
          // },
          formatter: '{value}',
        },
        handle: {
          show: true,
          icon: 'image',
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '概率',
      splitLine: {
        show: false,
      },
      //轴线的设置
      axisLine: {
        show: true,
      },
      //刻度
      axisTick: {
        show: true,
      },
    },
    // [
    //   // 左侧数值轴（供折线图使用）
    //   { type: 'value', name: '概率' },
    //   // 右侧类目轴（供柱状图使用）
    //   // {
    //   //   type: 'value',
    //   //   name: '价值',
    //   //   // data: ['Low', 'Medium', 'High'],
    //   //   position: 'right',
    //   // },
    // ],
    //布局组件
    grid: {
      left: 50,
      bottom: 80,
      right: 50,
      // top: 30,
    },
    //系列:决定显示图形图标是哪一种的
    series: [
      // {
      //   name: '价值',
      //   type: 'bar',
      //   yAxisIndex: 1,
      //   data: chartDataC.value, //价值
      //   //柱状图的:图形上的文本标签，
      //   label: {
      //     show: true,
      //     //文字的位置
      //     position: 'insideTop',
      //     //文字颜色
      //     color: 'black',
      //   },
      //   //是否显示背景颜色
      //   // showBackground: true,
      //   backgroundStyle: {
      //     //底部背景的颜色
      //     color: {
      //       type: 'linear',
      //       x: 0,
      //       y: 0,
      //       x2: 0,
      //       y2: 1,
      //       colorStops: [
      //         {
      //           offset: 0,
      //           color: 'black', // 0% 处的颜色
      //         },
      //         {
      //           offset: 1,
      //           color: 'blue', // 100% 处的颜色
      //         },
      //       ],
      //       global: false, // 缺省为 false
      //     },
      //   },
      //   //柱条的样式
      //   itemStyle: {
      //     borderRadius: [10, 10, 0, 0],
      //     //柱条颜色
      //     color: function (data: any) {
      //       //给每一个柱条这是背景颜色
      //       // let arr = [
      //       //   '#B0E0E6',
      //       //   '#FFB6C1',
      //       //   '#98FB98',
      //       //   '#DDA0DD',
      //       //   '#87CEEB', // 柔和粉彩
      //       //   '#9FE2BF',
      //       //   '#FFD700',
      //       //   '#40E0D0',
      //       //   '#6495ED',
      //       //   '#DA70D6', // 低饱和度
      //       //   '#E6E6FA',
      //       //   '#FFF0F5',
      //       //   '#F0FFF0',
      //       //   '#FFFACD',
      //       //   '#F5F5DC', // 奶油色
      //       // ]
      //       let arr = dynamicColors
      //       return arr[data.dataIndex]
      //     },
      //   },
      // },
      {
        name: '概率',
        type: 'line',
        yAxisIndex: 0,
        data: chartDataG.value, //[0.02, 0.05, 0.23, 0.22, 0.22, 0.22, 0.04],
        smooth: true, //平滑曲线
        label: {
          show: true,
          //文字的位置
          position: 'insideBottom',
          //文字颜色
          color: 'green',
        },
        color: '#ff1ec5',
        //区域填充样式
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(231, 152, 195, 0.5)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(13, 9, 232, 0.5)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
      },
    ],
  }
}

onMounted(() => {
  //一个容器可以同时展示多种类型的图形图标
  myChart.value = echarts.init(charts.value)
  //设置配置项
  myChart.value.setOption(setChart())
})
//组件挂载完毕
watch(chartsStatus, async (newVal, oldVal) => {
  if (newVal) {
    await nextTick() //等待DOM
    myChart.value = echarts.init(charts.value)
    myChart.value.setOption(setChart())
    ROI_status.value = false
  }
})
// onMounted(() => {

// })
</script>
<style scoped lang='scss'>
.resData {
  .el-textarea__inner {
    background-color: #d4efe200 !important;
  }
}

.json-input {
  margin: 10px 0;
}

.error-border {
  :deep(.el-textarea__inner) {
    border-color: #ff4d4f;
  }
}

.error-message {
  color: #ff4d4f;
  margin-top: 8px;
  font-size: 12px;
}
.gift_charts {
  height: 500px;
  width: 80%;
  margin-left: 10px;
}
</style>